package Server;

import Data.*;
import MyInterfaces.MassageType;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;

public class SendMassageToOther {
    //在群聊里面转发他人消息

    public boolean send(GroupMassageData groupMassageData) throws IOException, SQLException, NoSuchAlgorithmException, ClassNotFoundException {
        MassageData massageData=groupMassageData.getMassageData();
        ArrayList<GroupFriendData> arrayList=groupMassageData.getArrayList();

        if(massageData.getIs_file()==1)
        {
            GetFile getFile=new GetFile(massageData);
            massageData=getFile.getFile();
            if(massageData.getMD5()==null) return false;
        }
        else
        {
            InsertMassageToSql insert=new InsertMassageToSql(massageData);
            boolean is=insert.insertSql();
            if(!is) return false;
        }

        for (int i = 0; i < arrayList.size(); i++) {
            //转发消息
            if (arrayList.get(i).getId().equals(massageData.getSender())) continue;
            if (ManageClientConnectionServerThread.existId(arrayList.get(i).getId())) {
                Socket socket = ManageClientConnectionServerThread.getSocketByUserid(arrayList.get(i).getId());

                ObjectOutputStream wirter = new ObjectOutputStream(socket.getOutputStream());
                event massage = new event();
                massage.setType(MassageType.Send_Massage_To_Group);
                massage.setT(massageData);

                wirter.writeObject(massage);
                wirter.flush();

                System.out.println("服务器转发消息给" + arrayList.get(i).getId() + "消息为" + massageData.getContent());
            }
        }
        return true;
    }
}
